#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot
import numpy
import psycopg2

import cPickle as pickle
import glob
import sys

from util import *


def get_crawl_pop(cv_dirs):
  query = """SELECT COUNT(*) FROM
             (SELECT P.peer
              FROM peer_lists_%(suffix)s P
              GROUP BY P.peer)s"""
  conn = get_db_conn()
  c = conn.cursor()
  pops = []
  for dir in cv_dirs:
    s = get_db_suffix(dir)
    full_query = query % {'suffix': s}
    c.execute(full_query)
    pops.append((c.fetchone()[0], s))
  return pops


datafile = 'bt_pop.dat'
def plot_bittorrent_pop(cv_dirs):
  cv_dirs.sort()
  try:
    data = pickle.load(open(datafile, 'r'))
  except IOError:
    data = get_crawl_pop(cv_dirs)
    pickle.dump(data, open(datafile, 'w'), pickle.HIGHEST_PROTOCOL)
    
  pyplot.bar(range(len(data)), [x[0] for x in data], color='k')
  pyplot.xlabel('Crawl')
  pyplot.ylabel('# of IPs')
  pyplot.title('BitTorrent Popularity over time')
  pyplot.xticks([27.5, 30.5, 33.5, 36.5, 39.5, 42.5, 45.5],
                ['5/19', '5/20', '5/21', '5/22', '5/23', '5/24', '5/25'])

  pyplot.savefig('bt_pop_plot.png')

  
if __name__ == '__main__':
  plot_bittorrent_pop(glob.glob(sys.argv[1]))
